package com.sxt.sys.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sxt.sys.constast.SYSConstast;
import com.sxt.sys.domain.Role;
import com.sxt.sys.domain.User;
import com.sxt.sys.mapper.RoleMapper;
import com.sxt.sys.mapper.UserMapper;
import com.sxt.sys.service.UserService;
import com.sxt.sys.utils.DataGridView;
import com.sxt.sys.vo.RoleVo;
import com.sxt.sys.vo.UserVo;
@Service
@Transactional
public class UserServiceImpl implements UserService {
	@Autowired
   private UserMapper userMapper;
	@Autowired
	   private RoleMapper roleMapper;
	@Override
	public User login(User user) {
		// TODO Auto-generated method stub
		return this.userMapper.login(user);
	}
	@Override
	public DataGridView queryAllUser(UserVo userVo) {
		Page<Object> page = PageHelper.startPage(userVo.getPage(),
				userVo.getRows());
		List<User> list = this.userMapper.queryAllUser(userVo);
		return new DataGridView(page.getTotal(), list);
	}
	@Override
	public void addUser(UserVo userVo) {
		this.userMapper.insertSelective(userVo);
		
	}
	@Override
	public void updateUser(UserVo userVo) {
		// TODO Auto-generated method stub
		this.userMapper.updateByPrimaryKeySelective(userVo);
	}
	@Override
	public void deleteUser(UserVo userVo) {
		// TODO Auto-generated method stub
		this.userMapper.deleteByPrimaryKey(userVo.getUserid());
	}
	@Override
	public void saveUserRoles(UserVo userVo) {
		Integer userid=userVo.getUserid();
		Integer[] roleIds=userVo.getIds();
		//1,根据用户ID删除sys_role_user里面uid=userid的数据
		this.userMapper.deleteUserRoleByUserId(userid);
		//2,保存
		if(null!=roleIds&&roleIds.length>0){
			for (Integer rid : roleIds) {
				this.userMapper.saveUserRoles(userid,rid);
			}
		}
		
	}
	@Override
	public DataGridView queryUserRolesByUserId(Integer userid) {
		Role role=new Role();
		role.setAvailable(SYSConstast.AVAILABLE_TRUE);//
		List<Role> allRoles=roleMapper.queryAllRole(role);
		//2,查询当前用户拥有的角色
		List<Role> currUserRoles=this.roleMapper.queryRolesByUserId(userid);
		List<RoleVo> reList=new ArrayList<>();
		for (Role r1 : allRoles) {
			Boolean checked=false;
			for (Role r2 : currUserRoles) {
				if(r1.getRoleid()==r2.getRoleid()){
					checked=true;
					break;
				}
			}
			RoleVo roleVo = new RoleVo();
			//copy
			BeanUtils.copyProperties(r1, roleVo);
			roleVo.setChecked(checked);
			reList.add(roleVo);
		}
		return new DataGridView((long) reList.size(), reList);
	}
	@Override
	public void updateByPrimaryKeySelective(UserVo userVo) {
		// TODO Auto-generated method stub
		this.userMapper.updateByPrimaryKeySelective(userVo);
	}
  
}
